package com.example.pointxytest.activity;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ZipUtils;
import com.dy.net.mail.MailTool;
import com.example.pointxytest.BigDecimalUtil;
import com.example.pointxytest.Conts;
import com.example.pointxytest.R;
import com.example.pointxytest.widget.TouchImageView;
import com.example.pointxytest.widget.dialog.InputDialog;
import com.example.pointxytest.widget.popup.PopMenu;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.mail.event.TransportEvent;
import javax.mail.event.TransportListener;

public class Main1Activity extends AppCompatActivity implements View.OnClickListener{

    private RelativeLayout layImg;
    private TouchImageView touchImageView;
    private String sendMailres = "";
    private Uri uriDiTu,uriTuYa,uriFile;
    private PopMenu mPopMenu;
    private Bitmap bmTuYa;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        uriDiTu = getIntent().getParcelableExtra("uriDiTu");
        uriTuYa = getIntent().getParcelableExtra("uriTuYa");
        uriFile = getIntent().getParcelableExtra("uriFile");

        layImg = findViewById(R.id.lay_img);
        findViewById(R.id.fab_menu).setOnClickListener(this::onClick);

        ImageView ivDiTu = findViewById(R.id.iv_ditu);
        ivDiTu.setImageURI(uriDiTu);
        ViewTreeObserver vto = ivDiTu.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if(touchImageView == null){
                    try {
                        InputStream fis = getContentResolver().openInputStream(uriTuYa);
                        Bitmap bitmap = BitmapFactory.decodeStream(fis);
                        touchImageView = new TouchImageView(Main1Activity.this,ivDiTu,bitmap);
                        layImg.addView(touchImageView,new RelativeLayout.LayoutParams(ivDiTu.getWidth(),ivDiTu.getHeight()));
                        fis.close();
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        mPopMenu = new PopMenu(this,getIntent().getStringExtra("email"));
        mPopMenu.setOnDialogClick((i, str) -> {
            switch (i){
                case 0:
                    InputDialog inputDialog = new InputDialog(Main1Activity.this,"请输入邮箱",mPopMenu.getEmail());
                    inputDialog.setOnDialogClick((i1, str1) -> mPopMenu.setEmail(str1));
                    inputDialog.show();
                    break;
                case 1:
                    calculatePointAndBitmap();
                    break;
            }
        });
    }

    private ArrayList<float[]> getPointsOnLine(Uri uri){

        ArrayList<float[]> points = new ArrayList<>();
        try {
            InputStream fis = getContentResolver().openInputStream(uri);
            DataInputStream dis = new DataInputStream(fis);
            String strLine = null;
            while ((strLine = dis.readLine()) != null){
                if(strLine.length() > 0 || strLine.contains(",")){
                    String str[] = strLine.split(",");
                    float[] floats = new float[]{Float.parseFloat(str[0]),Float.parseFloat(str[1])};
                    points.add(floats);
                }
            }
            dis.close();
            fis.close();
        }catch (Exception e){}
        return points;
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        switch (id){
            case R.id.fab_menu:
                mPopMenu.showAsDropDown(view);
                break;
        }
    }

    private void calculatePointAndBitmap(){
        List<float[]> points = getPointsOnLine(uriFile);
        touchImageView.transformPoints(points);

        StringBuilder sb = new StringBuilder();
        for(float[] point: points){
            sb.append(BigDecimalUtil.setScale(0,String.valueOf(point[0])))
                    .append(",")
                    .append(BigDecimalUtil.setScale(0,String.valueOf(point[1])))
                    .append("\r\n");
        }

        new Thread(() -> {
            Bitmap bitmap0 = null;
            try {
                InputStream fis = getContentResolver().openInputStream(uriDiTu);
                bitmap0 = BitmapFactory.decodeStream(fis);
                fis.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            Bitmap mmBitmap = bitmap0.copy(bitmap0.getConfig(), true);
            Canvas canvas = new Canvas(mmBitmap);
            canvas.setDrawFilter(new PaintFlagsDrawFilter(0, Paint.ANTI_ALIAS_FLAG|Paint.FILTER_BITMAP_FLAG));
            Paint paint = new Paint();
            paint.setAntiAlias(true);
            paint.setColor(0xffFF00C6);
            paint.setStrokeWidth(3);
            for(int i = 1; i < points.size(); i++){
                canvas.drawLine(points.get(i-1)[0],points.get(i-1)[1],points.get(i)[0],points.get(i)[1],paint);
            }
            FileOutputStream outputStream = null;
            File file = new File(Conts.bitmapAndPathSavePath + System.currentTimeMillis() +  "_2.png");
            file.getParentFile().mkdirs();
            deleteFile(file.getParentFile());
            try {
                outputStream = new FileOutputStream(file);
                mmBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if(outputStream != null) outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            runOnUiThread(() -> {
                new myTask().execute(sb.toString());
                ImageView iv = new ImageView(Main1Activity.this);
                iv.setImageBitmap(mmBitmap);
                AlertDialog.Builder dialog = new AlertDialog.Builder(Main1Activity.this);
                dialog.setView(iv).show();
            });
        }).start();
    }

    @SuppressLint("StaticFieldLeak")
    class myTask extends AsyncTask<String,String,String> {
        @Override
        protected String doInBackground(String... strs) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd-HH-mm-ss");
            String timeStr = simpleDateFormat.format(new Date());
            String pathFileName = timeStr+"_pointResult.txt";
            File file = new File(Conts.bitmapAndPathSavePath+pathFileName);
            try {
                if (file.exists()){
                    file.delete();
                }
                if (!file.getParentFile().exists()){
                    file.getParentFile().mkdirs();
                }
                file.createNewFile();
                FileWriter fileWriter = new FileWriter(file);
                fileWriter.write(strs[0]);
                fileWriter.flush();
                fileWriter.close();

                File[] files = new File(Conts.bitmapAndPathSavePath).listFiles();
                Collection<File> collection = Arrays.asList(files);
                File zipfile = new File(Conts.bitmapAndPathSavePath + "pngAndPath.zip");
                ZipUtils.zipFiles(collection, zipfile);
                String address = mPopMenu.getEmail();
                SPUtils.getInstance().put(Conts.EMAIL_KEY,address);
                MailTool.sendEmail(address, zipfile, new TransportListener() {
                    @Override
                    public void messageDelivered(TransportEvent e) {
                        sendMailres = "发送邮件成功！";
                    }

                    @Override
                    public void messageNotDelivered(TransportEvent e) {

                    }

                    @Override
                    public void messagePartiallyDelivered(TransportEvent e) {

                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                return e.getMessage();
            }
            return "ok,写入文件 并发送邮件成功!!!!!"+sendMailres;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Toast.makeText(Main1Activity.this,s,Toast.LENGTH_LONG).show();
        }
    }

    public static void deleteFile(File file) {
        if (file.exists()) {
            if (file.isFile()) {
                file.delete();
            } else if (file.isDirectory()) {
                File files[] = file.listFiles();
                for (int i = 0; i < files.length; i++) {
                    deleteFile(files[i]);
                }
            }
//            file.delete();
        } else {
            Log.e("TAG", "delete file no exists " + file.getAbsolutePath());
        }
    }

}
